package com.hivis.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


public class EncryptUtil {
	
    /* 1、指定DES加密解密所用的密钥 */  
    private Key key;

    public EncryptUtil(String seed){
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            generator.init(new SecureRandom(seed.getBytes()));
            this.key = generator.generateKey();
            generator = null;
        } catch (NoSuchAlgorithmException e) {
            ///throw(new RuntimeException(e.getMessage(), e);  );
        }
    }
    
    /**
     * 对字符串进行DES加密，返回BASE64编码的加密字符串
     * @param src
     * @return
     */
    public String encrypt(String src/* 明文 */) {
        try {  
            byte[] src_byte = src.getBytes("UTF-8");  
            Cipher cipher = Cipher.getInstance("DES");  
            cipher.init(Cipher.ENCRYPT_MODE, key);  
            byte[] final_byte = cipher.doFinal(src_byte);  
            return Base64.encodeBase64String(final_byte);  
        } /* 
         * catch (UnsupportedEncodingException e) { log.info(e.getMessage(), e); 
         * } catch (NoSuchAlgorithmException e) { log.info(e.getMessage(), e); } 
         * catch (NoSuchPaddingException e) { log.info(e.getMessage(), e); } 
         */catch (Exception e) {  
            throw new RuntimeException(e.getMessage(), e);  
        }  
    }
    
    /**
     * 对BASE64编码的加密字符串进行解密，返回解密后的字符串
     * @param src 密文 
     * @return
     */
    public String decrypt(String src) {
        try {  
            byte[] src_byte = Base64.decodeBase64(src);
            Cipher cipher = Cipher.getInstance("DES");  
            cipher.init(Cipher.DECRYPT_MODE, key);  
            byte[] decrypt_byte = cipher.doFinal(src_byte);  
            return new String(decrypt_byte, "UTF-8");  
        } catch (Exception e) {  
            throw new RuntimeException(e.getMessage(), e);  
        }  
    }  

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
